/***************************************************************************
 *   copyright : (C) 2009 Udrea Cristian
 *   site : http://code.google.com/p/testauction-php
 ***************************************************************************/

/***************************************************************************
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU Lesser General Public License as 
 *   published by the Free Software Foundation; either version 2 of the
 *   License, or (at your option) any later version. Although none of the
 *   code may be sold. If you have been sold this script, get a refund.
 ***************************************************************************/
#include <time.h>
#include <stdio.h>
#include <string.h>
#include <windows.h>
#include <winsock2.h>

int main (int argc, char *argv[]) {
  time_t rawtime;
  struct tm * now;
  double left;
  int dt = 1;
  
  SOCKET lhSocket;
  SOCKADDR_IN lSockAddr;
  WSADATA wsaData;
  int lConnect;
  int lLength;

  if(argc != 3) {
        printf("Wrong number of parameters!\n");
	exit(1);
  }

  printf("Preparing Server Cron Job ...\n");

  if(WSAStartup(MAKEWORD(2,0),&wsaData) != 0) {
	printf("Socket Initialization Error. Program aborted\n");
	return 1;
  }

  memset(&lSockAddr,0, sizeof(lSockAddr));
  lSockAddr.sin_family = AF_INET;
  lSockAddr.sin_port = htons(80);
  lSockAddr.sin_addr.s_addr = inet_addr(argv[1]);

  printf("Server Cron Job Started...\n");

  while(1) {
    time(&rawtime);
    now = localtime(&rawtime);
    left = dt - (now->tm_sec % dt);
    Sleep((int)left*1000);

    //printf("Interval = %d ms\n", (int)left); 

	lhSocket = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
	if(lhSocket == INVALID_SOCKET) {
		printf("Invalid Socket ");
		printf("%ld", GetLastError());
		printf(". Program Aborted\n");
	}
	lConnect = connect(lhSocket, (SOCKADDR *)&lSockAddr, sizeof(SOCKADDR_IN));
	if(lConnect != 0) {
		printf("Connect Error. Program aborted\n");
		closesocket(lhSocket);
		continue;
		//return 2;
	}
	lLength = send(lhSocket, "GET ", strlen("GET "), 0);
	lLength = send(lhSocket, argv[2], strlen(argv[2]), 0);
	lLength = send(lhSocket, "\n\n", strlen("\n\n"), 0);
	closesocket(lhSocket);
  }
  return 0;
}
